import ProTable from '@/components/proTable';
import useAccessList from '@/hooks/useAccessList';
import Tools from '@/utils/tools';
import { useModel } from '@umijs/max';
import { TableProps } from 'antd';
import dayjs from 'dayjs';
import Operation from './components/operation';
import Status from './components/status';
import { DataType } from './constant';
import { createAccessKey, disableAccessKey, readAccessKey } from './service';

const AccessKey: React.FC = () => {
  const { userId } = useModel('global');
  const { loading, data, setFresh } = useAccessList();

  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'AccessKey',
      dataIndex: 'accessKey',
      key: 'accessKey',
    },
    {
      title: 'accessSecret',
      dataIndex: 'accessSecret',
      key: 'accessSecret',
      hidden: true,
    },
    {
      title: '状态',
      dataIndex: 'enable',
      key: 'enable',
      render: (_, record) => {
        return <Status disable={record.disable} />;
      },
    },
    {
      title: '最后使用时间',
      dataIndex: 'lastUsedTime',
      key: 'lastUsedTime',
      render: (text) => {
        if (!text) return '--';
        return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '已创建时间',
      key: 'duration',
      dataIndex: 'duration',
      render: (_, record) => {
        const { createTime } = record;
        return Tools.durationFormat(createTime, dayjs().toString());
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        return (
          <Operation
            record={record}
            readAccessKey={readAccessKey}
            disableAccessKey={() => disableAccessKey(record, userId, setFresh)}
          />
        );
      },
    },
  ];
  return (
    <ProTable
      title="AccessKey"
      buttonText="创建AccessKey"
      buttonAction={() => createAccessKey(userId, setFresh)}
      columns={columns}
      data={data}
      loading={loading}
      rowClassName={(record: DataType) =>
        record.disable === 0 ? '' : 'disabledRow'
      }
    />
  );
};
export default AccessKey;
